<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="患者id" prop="patientId">
        <el-input
            v-model="queryParams.patientId"
            placeholder="请输入患者id"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="入院时间" prop="admissionTime">
        <el-date-picker clearable
                        v-model="queryParams.admissionTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择入院时间">
        </el-date-picker>
      </el-form-item>

<!--      <el-form-item label="紧急联系人编号" prop="emergencyContactId">-->
<!--        <el-select v-model="queryParams.emergencyContactId" placeholder="请选择紧急联系人编号" clearable>-->
<!--          <el-option-->
<!--              v-for="dict in relationships_contacts"-->
<!--              :key="dict.value"-->
<!--              :label="dict.label"-->
<!--              :value="dict.value"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['nurse:beinhospital:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['nurse:beinhospital:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['nurse:beinhospital:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['nurse:beinhospital:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="beinhospitalList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="患者姓名" align="center" prop="realName">
        <template #default="scope">
          <el-link type="primary" @click="handleViewPatient(scope.row.patientId)">{{ scope.row.realName }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="入院时间" align="center" prop="admissionTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.admissionTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="科室id" align="center" prop="departmentId" />-->
      <el-table-column label="医生科室" align="center" prop="doctorDepartmentName" />
      <!--      <el-table-column label="床位号" align="center" prop="bedNumber" />-->
      <el-table-column label="床位号" align="center" prop="bedNumber">
        <template #default="scope">
          <el-link type="primary" @click="handleViewBed(scope.row.bedNumber)">{{ scope.row.bedNumber }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="医生姓名" align="center" prop="doctorName" />
      <el-table-column label="护士姓名" align="center" prop="nurseName" />
<!--      <el-table-column label="紧急联系人编号" align="center" prop="emergencyContactId">-->
<!--        <template #default="scope">-->
<!--          <dict-tag :options="relationships_contacts" :value="scope.row.emergencyContactId"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['nurse:beinhospital:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['nurse:beinhospital:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 床位详细信息对话框 -->
    <el-dialog :title="bedDetailTitle" v-model="bedDetailOpen" width="500px" append-to-body>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="床位号">{{ bedDetail.bedNumber }}</el-descriptions-item>
        <el-descriptions-item label="床位状态">{{ bedDetail.bedStatus === 1 ? '占用' : '可用' }}</el-descriptions-item>
        <el-descriptions-item label="病房号">{{ bedDetail.mwardInfo.wardNumber }}</el-descriptions-item>
        <el-descriptions-item label="病房位置">{{ bedDetail.mwardInfo.wardAdress }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 患者详细信息对话框 -->
    <el-dialog :title="patientDetailTitle" v-model="patientDetailOpen" width="600px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="患者姓名">{{ patientDetail.realName }}</el-descriptions-item>
        <el-descriptions-item label="患者ID">{{ patientDetail.patientId }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ patientDetail.gender }}</el-descriptions-item>
        <el-descriptions-item label="年龄">{{ patientDetail.age }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{patientDetail.phoneNumber }}</el-descriptions-item>
        <el-descriptions-item label="地址">{{ patientDetail.address }}</el-descriptions-item>
<!--        <el-descriptions-item label="紧急联系人">{{ patientDetail.emergencyContactId }}</el-descriptions-item>-->
      </el-descriptions>

      <h3>就诊记录</h3>
      <el-table :data="patientDetail.mvisitRecordList" style="width: 100%">
        <el-table-column label="就诊时间" prop="visitTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.visitTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="初步诊断" prop="preliminaryDiagnosis" />
        <el-table-column label="治疗建议" prop="treatmentAdvice" />
      </el-table>
    </el-dialog>

    <!-- 添加或修改住院登记对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="beinhospitalRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="患者姓名" prop="realName">
          <el-select v-model="form.realName" placeholder="请选择患者姓名" filterable @change="handlePatientChange">
            <el-option
                v-for="patient in patientList"
                :key="patient.patientId"
                :label="patient.realName"
                :value="patient.realName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="入院时间" prop="admissionTime">
          <el-date-picker clearable
                          v-model="form.admissionTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择入院时间">
          </el-date-picker>
        </el-form-item>
        <!--        <el-form-item label="科室id" prop="departmentId">-->
        <!--          <el-input v-model="form.departmentId" placeholder="请输入科室id" />-->
        <!--        </el-form-item>-->
<!--        <el-form-item label="紧急联系人编号" prop="emergencyContactId">-->
<!--          <el-select v-model="form.emergencyContactId" placeholder="请选择紧急联系人编号">-->
<!--            <el-option-->
<!--                v-for="dict in relationships_contacts"-->
<!--                :key="dict.value"-->
<!--                :label="dict.label"-->
<!--                :value="parseInt(dict.value)"-->
<!--            ></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->

        <!-- 添加床位号选择 -->
        <el-form-item label="床位号" prop="bedNumber">
          <el-select v-model="form.bedNumber" placeholder="请选择床位号" filterable @change="handleBedChange">
            <el-option
                v-for="bed in bedList"
                :key="bed.bedId"
                :label="bed.bedNumber"
                :value="bed.bedNumber"
                :disabled="bed.bedStatus === 1"
            />
          </el-select>
        </el-form-item>
        <!-- 添加床位状态显示 -->
        <el-form-item label="床位状态" prop="bedStatus">
          <el-input v-model="form.bedStatusText" disabled></el-input>
        </el-form-item>


        <el-form-item label="护士姓名" prop="nurseId">
          <el-select v-model="form.nurseId" placeholder="请选择护士" filterable>
            <el-option
                v-for="emp in employeeList"
                :key="emp.id"
                :label="emp.name"
                :value="emp.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Beinhospital">
import { listBeinhospital, getBeinhospital, delBeinhospital, addBeinhospital, updateBeinhospital,listjiuzhen,getMEmoployee2,getMdepartment,getMdepartment2  } from "@/api/nurse/beinhospital";
import {listBed, updateBed} from "@/api/nurse/bed.js";

const { proxy } = getCurrentInstance();
const { relationships_contacts } = proxy.useDict('relationships_contacts');

const beinhospitalList = ref([]); //存储患者的住院记录
const patientList = ref([]); // 存储患者列表
const employeeList = ref([]); //存储所有员工的信息
const departmentList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const bedList = ref([]); // 添加床位列表


const bedDetailOpen = ref(false); // 控制床位详情弹框的显示
const bedDetail = ref({}); // 存储床位详情数据
const bedDetailTitle = ref("床位详细信息");

function handleViewBed(bedNumber) {
  console.log("床位号")
  console.log(bedNumber)
  // 调用 listBed 接口查询床位详情
  listBed({ bedNumber: bedNumber }).then(response => {
    if (response && response.rows && response.rows.length > 0) {
      bedDetail.value = response.rows[0]; // 设置床位详情数据
      bedDetailOpen.value = true; // 打开弹框
      console.log("Aaaaa")
      console.log(bedDetail.value);
    } else {
      proxy.$modal.msgError("未找到该床位信息");
    }
  }).catch(error => {
    console.error("查询床位信息失败：", error);
    proxy.$modal.msgError("查询床位信息失败");
  });
}




// 当选择床位时更新床位状态
function handleBedChange(value) {
  const selectedBed = bedList.value.find(bed => bed.bedNumber === value);
  if (selectedBed) {
    form.value.bedStatusText = selectedBed.bedStatus === 0 ? '可用' : '占用';
  } else {
    form.value.bedStatusText = '未知';
  }
}


function getBedList() {
  listBed().then(response => {
    // 过滤出状态为 0（可用）的床位
    bedList.value = response.rows.filter(bed => bed.bedStatus === 0) || [];
  }).catch(error => {
    console.error("Failed to fetch bed list:", error);
  });
}
// 弹框
const patientDetailOpen = ref(false); // 控制患者详细信息对话框的显示
const patientDetail = ref({}); // 存储患者详细信息
const patientDetailTitle = ref("患者详细信息");







function handleViewPatient(patientId) {
  // 根据 patientId 查找对应的患者详细信息
  const patient = patientList.value.find(p => p.patientId === patientId);
  if (patient) {
    patientDetail.value = patient; // 设置患者详细信息
    patientDetailOpen.value = true; // 打开对话框
  } else {
    console.error("Patient not found:", patientId);
  }
}





onMounted(() => {
  console.log("患者信息")
  console.log(patientList.value);
});

const data = reactive({
  form: {
    bedStatusText: '' // 添加床位状态字段
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    patientId: null,
    admissionTime: null,
    departmentId: null,
    bedNumber: null,
    doctorId: null,
    emergencyContactId: null,
    nurseId: null,
    ext1: null,
    ext2: null,
    ext3: null,
    ext4: null,
    ext5: null
  },
  rules: {
    patientId: [
      { required: true, message: "患者id不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);
//查最新的就诊记录
function findLatestVisitRecord(visitRecords) {
  if (!visitRecords || visitRecords.length === 0) {
    return null;
  }
  // 按就诊时间排序，找到最新的记录
  visitRecords.sort((a, b) => {
    const timeA = new Date(a.visitTime || 0);
    const timeB = new Date(b.visitTime || 0);
    return timeB - timeA; // 降序排序
  });
  return visitRecords[0]; // 返回最新的记录
}
function handlePatientChange(value) {
  const selectedPatient = patientList.value.find(patient => patient.realName === value);
  if (selectedPatient) {
    const visitRecords = selectedPatient.mvisitRecordList || [];

    // 找到时间最新的就诊记录
    const latestVisitRecord = findLatestVisitRecord(visitRecords);

    if (latestVisitRecord) {
      // 将最新就诊记录中的医生ID填充到表单中
      form.value.doctorId = latestVisitRecord.doctorId;
    } else {
      console.warn("No visit records found for patient:", selectedPatient.patientId);
    }
  }
}



async function getList() {
  loading.value = true;
  try {
    const response = await listBeinhospital(queryParams.value);
    beinhospitalList.value = await Promise.all(response.rows.map(async (item) => {
      // 根据 patientId 查找对应的患者姓名
      const patient = patientList.value.find(p => p.patientId === item.patientId);
      // 根据 doctorId 查找对应的医生姓名
      const doctor = employeeList.value.find(emp => emp.id === item.doctorId);
      // 根据 nurseId 查找对应的护士姓名
      const nurse = employeeList.value.find(emp => emp.id === item.nurseId);

      // 默认科室名称
      let doctorDepartmentName = null;
      // 如果医生信息存在且有 departmentId，则查询科室信息
      if (doctor && doctor.departmentId) {
        try {
          const departmentResponse = await getMdepartment(doctor.departmentId);
          console.log("部门信息");
          console.log(departmentResponse);
          doctorDepartmentName = departmentResponse.departmentName;
          console.log(doctorDepartmentName);
        } catch (error) {
          console.error("Failed to fetch department name:", error);
        }
      }

      console.log("666");
      console.log(doctorDepartmentName);

      return {
        ...item,
        realName: patient ? patient.realName : "未知", // 患者姓名
        doctorName: doctor ? doctor.name : "未知",     // 医生姓名
        doctorDepartmentName: doctorDepartmentName,   // 医生科室名称
        nurseName: nurse ? nurse.name : "未知",       // 护士姓名
      };
    }));

    total.value = response.total;
  } catch (error) {
    console.error("Failed to fetch beinhospital list:", error);
  } finally {
    loading.value = false;
  }
}

// 222
function getemployeeList() {
  getMEmoployee2().then((response) => {
    console.log("员工信息")
    console.log(response)
    employeeList.value = response || []; // 假设后端返回所有员工信息
  }).catch(error => {
    console.error("Failed to fetch employee list:", error);
  });
}


function getMdepartments(){
  getMdepartment2().then((response) => {
    console.log(response)
    departmentList.value = response || []; //返回所有的科室信息
  })
}


function getPatientList() {
  listjiuzhen().then((response) => {
    console.log(response)
    patientList.value = response || []; // 假设后端返回患者列表
  });
}


// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    registrationId: null,
    patientId: null,
    admissionTime: null,
    departmentId: null,
    bedNumber: null,
    doctorId: null,
    emergencyContactId: null,
    nurseId: null,
    ext1: null,
    ext2: null,
    ext3: null,
    ext4: null,
    ext5: null
  };
  proxy.resetForm("beinhospitalRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.registrationId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加住院登记";
  // 获取可用的床位列表
  getBedList();
  // 初始化床位状态为 1（占用状态）
  form.value.bedStatusText = '占用';


  // 假设已经在表单中选择了患者姓名，获取患者ID
  const selectedPatient = patientList.value.find(patient => patient.realName === form.value.realName);
  if (selectedPatient) {
    const patientId = selectedPatient.patientId;

    // 从患者对象中获取就诊记录列表
    const visitRecords = selectedPatient.mvisitRecordList || [];

    // 找到时间最新的就诊记录
    const latestVisitRecord = findLatestVisitRecord(visitRecords);

    if (latestVisitRecord) {
      // 将最新就诊记录中的医生ID填充到表单中
      form.value.doctorId = latestVisitRecord.doctorId;
    } else {
      console.warn("No visit records found for patient:", patientId);
    }
  }
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _registrationId = row.registrationId || ids.value;
  getBeinhospital(_registrationId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改住院登记";
    getBedList(); // 获取可用的床位列表

    // 初始化床位状态显示
    const selectedBed = bedList.value.find(bed => bed.bedNumber === form.value.bedNumber);
    if (selectedBed) {
      form.value.bedStatusText = selectedBed.bedStatus === 0 ? '可用' : '占用';
    } else {
      form.value.bedStatusText = '未知';
    }
  });
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["beinhospitalRef"].validate(async valid => {
    if (valid) {
      try {
        // 根据患者姓名查找患者ID
        const selectedPatient = patientList.value.find(patient => patient.realName === form.value.realName);
        if (selectedPatient) {
          form.value.patientId = selectedPatient.patientId; // 设置患者ID
        }

        // 如果是修改操作，获取原床位信息
        let originalBedNumber = null;
        if (form.value.registrationId != null) {
          const originalRecord = await getBeinhospital(form.value.registrationId);
          originalBedNumber = originalRecord.data.bedNumber;
        }

        // 提交住院登记
        if (form.value.registrationId != null) {
          await updateBeinhospital(form.value);
          proxy.$modal.msgSuccess("修改成功");
        } else {
          await addBeinhospital(form.value);
          proxy.$modal.msgSuccess("新增成功");
        }

        // 如果修改了床位，更新原床位状态为 0（空闲状态）
        if (originalBedNumber && originalBedNumber !== form.value.bedNumber) {
          await updateBedStatusByBedNumber(originalBedNumber, 0);
        }

        // 更新新床位状态为 1（占用状态）
        if (form.value.bedNumber) {
          await updateBedStatusByBedNumber(form.value.bedNumber, 1);
        }

        open.value = false;
        getList();
      } catch (error) {
        console.error("提交失败：", error);
        proxy.$modal.msgError("提交失败");
      }
    }
  });
}


async function updateBedStatusByBedNumber(bedNumber, bedStatus) {
  try {
    // 1. 根据 bedNumber 查询病床信息
    const bedInfo = await getBedInfoByBedNumber(bedNumber);
    const bedId = bedInfo.bedId;

    // 2. 更新病床状态
    await updateBedStatus(bedId, bedStatus);
    console.log("病床状态更新成功");
  } catch (error) {
    console.error("更新病床状态失败：", error);
    throw error; // 抛出错误以便在调用处处理
  }
}

function getBedInfoByBedNumber(bedNumber) {
  return listBed({ bedNumber }).then(response => {
    if (response && response.rows && response.rows.length > 0) {
      return response.rows[0]; // 返回第一条匹配的病床信息
    } else {
      throw new Error("未找到对应的病床信息");
    }
  });
}
function updateBedStatus(bedId, bedStatus) {
  const data = {
    bedId: bedId,
    bedStatus: bedStatus // 1 表示占用，0 表示空闲
  };
  return updateBed(data);
}





/** 删除按钮操作 */
function handleDelete(row) {
  const _registrationIds = row.registrationId || ids.value;
  proxy.$modal.confirm('是否确认删除住院登记编号为"' + _registrationIds + '"的数据项？').then(function() {
    return delBeinhospital(_registrationIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('nurse/beinhospital/export', {
    ...queryParams.value
  }, `beinhospital_${new Date().getTime()}.xlsx`)
}

getList();
getPatientList(); // 加载时获取患者列表
getemployeeList();
// getWardList(); // 获取病房列表
getBedList(); // 获取可用的床位列表
</script>